// src/guards/rbac.guard.ts
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  ForbiddenException,
} from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RbacGuard implements CanActivate {
  // role[用户角色]: 0-超级管理员 | 1-管理员 | 2-开发&测试&运营 | 3-普通用户（只能查看）
  constructor(private readonly roles: string) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const reqRoles = request.user.roles.split(',');
    const thisRoles = this.roles.split(',');
    const roleArr = reqRoles.concat(thisRoles).filter(function (v, i, arr) {
      return arr.indexOf(v) === arr.lastIndexOf(v);
    });

    if (!roleArr.length) {
      throw new ForbiddenException('对不起，您无权操作');
    }
    return true;
  }
}
